import cv2
import numpy as np
import time
import math
import logging


# 根据二值化图像生成跟踪点 
def traget_bias_generate(binary_image, search_line, search_width):
    """
    binary_image: 二值化图像(480, 640)
    """
    height, width = binary_image.shape
    # 计算图像的高度和宽度
    line = binary_image[search_line][search_width:-search_width]
    
    black_regions = []
    in_black_region = False
    start_idx = -1
    
    for i in range(len(line)):
        if line[i] == 255:  # 白色像素
            if not in_black_region:  # 如果当前不是在白色区域中，说明是黑色区域的开始
                start_idx = i
                in_black_region = True
        else:  # 黑色像素
            if in_black_region:  # 如果当前是黑色区域，且之前有白色区域，说明白色区域结束
                black_regions.append([start_idx, i - 1, i - start_idx])
                in_black_region = False

    # 如果没检测到
    if len(black_regions) == 0:
        # logging.warning("don't get black region")
        return -1
    # 如果行的最后部分仍然是白色区域
    if in_black_region:
        black_regions.append([start_idx, len(line) - 1, len(line) - start_idx])
    max_idx, max_len = 0, black_regions[0][2]

    for i in range(len(black_regions)):
        if black_regions[i][2] > max_len:
            max_len = black_regions[i][2]
            max_idx = i

    center = (black_regions[max_idx][0] + black_regions[max_idx][1]) // 2  # 计算白色区域的中心
    return -round(float((width//2 - (center + search_width))/(width//2)), 3)  # 返回中心点的坐标

# 判断任务路标："T"型

def judge_task_signal(binary_image, threshold, case):
    """
    binary_image: 二值化图像(480, 640)
    threshold: 白色区域占比阈值
    case: {"x0": 0, "y0": 0, "x1": 640, "y1": 480}
    """
    roi = binary_image[case["y0"]:case["y1"], case["x0"]:case["x1"]]
    black_pixels = cv2.countNonZero(roi)
    total_pixels = roi.size
    if total_pixels == 0:
        total_pixels = 1
    black_ratio = black_pixels / total_pixels
    # print(f'黑色像素占比: {black_ratio:.2f}, {black_pixels},{total_pixels}')
    if black_ratio > threshold:
        return True, black_ratio
    else:
        return False, black_ratio
